package main

import (
	"encoding/json"
	"fmt"
	"html/template"
	"io/ioutil"
	"net/http"
)

func main() {
	http.HandleFunc("/", IndexPage)
	http.HandleFunc("/managerlog", ManagerLog)
	http.HandleFunc("/applog", AppLog)
	http.HandleFunc("/networklog", NetLog)
	http.HandleFunc("/config", Config)
	http.HandleFunc("/case/post",RunCase)
	http.HandleFunc("/case/get",getResults)

	//指定相对路径./dist 为文件服务路径
	staticHandle := http.FileServer(http.Dir("./dist"))
	//将/js/路径下的请求匹配到 ./dist/js/下
	http.Handle("/js/", staticHandle)
	http.Handle("/css/", staticHandle)
	http.Handle("/fonts/", staticHandle)

	fmt.Println("服务器即将开启，访问地址 http://localhost:8080")
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		fmt.Println("服务器开启错误: ", err)
	}
}

func IndexPage(writer http.ResponseWriter, request *http.Request)  {
	t,_ := template.ParseFiles("./dist/index.html")
	t.Execute(writer,nil)
}

func ManagerLog(writer http.ResponseWriter, request *http.Request)  {
	writer.Write([]byte("manager:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n"))
}

func AppLog(writer http.ResponseWriter, request *http.Request)  {
	writer.Write([]byte("applog: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n"))
}

func NetLog(writer http.ResponseWriter, request *http.Request)  {
	writer.Write([]byte("netlog: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n"))
}

func Config(writer http.ResponseWriter, request *http.Request)  {
	fmt.Println("config is changed:")
}

func RunCase(writer http.ResponseWriter, request *http.Request)  {
	fmt.Println("some case will to be run:")
	res, _ := ioutil.ReadAll(request.Body)
	fmt.Println(string(res))
	request.Body.Close()

	m := make(map[string]interface{})
	json.Unmarshal(res, m)
	fmt.Println(m)
}

type result struct {
	fail []int
	pass []int
}
func getResults(writer http.ResponseWriter, request *http.Request)  {
	fmt.Println("receive results request:")
	results := result{
		fail: []int{1,3,5},
		pass: []int{7,8,9},
	}
	b,err := json.Marshal(results)
	if err != nil {
		fmt.Println("error:", err)
	}
	writer.Write(b)
}
